#include "IniHandle/IniHandleApi.h"
#include "piccache.h"
#include <cstdio>
#include <iostream>


#include <time.h>

static int file_cnt = 0;
static int file_cur = 0;

static bool status_wait = false; 
static time_t start_time = 0;
static time_t cur_time = 0;


inline int findNumberPart(const QString& sIn, int backlen=4, int back_filter_len=4)
{
  //QString s = sIn.right(4);
  int len = sIn.length();
  QString s = sIn.mid(len-(back_filter_len+backlen), backlen);
  
  //qDebug()<<"findNumberPart:"<<s;

  return s.toInt();
}


bool nauralSortCallback(const QFileInfo& s1, const QFileInfo& s2, int backlen=4, int back_filter_len=4)
{
  int idx1 = findNumberPart(s1.fileName(), backlen, back_filter_len);
  int idx2 = findNumberPart(s2.fileName(), backlen, back_filter_len);
  return (idx1 < idx2);

}

PicCache::PicCache(QDir *dirInput, int wait_time)
{
    piccache_wait_time = wait_time;

    dir = dirInput;
    dir->setFilter(QDir::Files|QDir::Hidden|QDir::NoSymLinks);
    //dir->setSorting(QDir::Time|QDir::Reversed); //dir->setSorting(QDir::Name);
        
    //std::string front_filter = GetStringValueKeyIni("Filter", "front_filter", "101"); 
    //std::string back_filter = GetStringValueKeyIni("Filter", "back_filter", ".jpg");
    
    back_order_length = GetIntegerKeyIni("BackOrder", "back_order_length", 4); 

    front_filter = GetStringValueKeyIni("Filter", "front_filter", ""); 
    back_filter = GetStringValueKeyIni("Filter", "back_filter", "");
    std::string namefilter = front_filter+"*"+back_filter;
    QString namefilter_qstr = QString::fromStdString(namefilter);

    qDebug()<<"namefilter:"<<namefilter_qstr;

    QStringList filters;
    //filters << "*.jpg";
    filters << namefilter_qstr;

    dir->setNameFilters(filters);

    fileList = dir->entryInfoList();
    qSort(fileList.begin(), 
          fileList.end(), 
          std::bind(nauralSortCallback, 
                    std::placeholders::_1, 
                    std::placeholders::_2, 
                    back_order_length,
                    back_filter.size())
          );
    //qSort(fileList.begin(), fileList.end(), nauralSortCallback);

    picList = new QList<struct pic>;
    readCount = 0;
    uavCount = 0;
    oldFileCount = 0;
    picHeight = 0;
    picWidth = 0;
}

void PicCache::run()
{   //readCount是读取文件的总个数，newCount是当前循环新增文件的个数
    //fileList是文件信息的总列表，newFileList是当前循环的差量列表
    while (1)
    {
        oldFileCount = dir->count();//刷新之前文件的个数
        dir->refresh();

        fileList = dir->entryInfoList();
        //qSort(fileList.begin(), fileList.end(), nauralSortCallback);
        qSort(fileList.begin(), 
              fileList.end(), 
              std::bind(nauralSortCallback, 
                        std::placeholders::_1, 
                        std::placeholders::_2, 
                        back_order_length,
                        back_filter.size())
              );
        //newFileList = dir->entryInfoList();

        newFileList.clear();

        //newFileList = newFileList.mid(oldFileCount);//从新列表中剔除旧的列表中的内容，增量修改
        
        //static int file_cnt = 0;
        //static int file_cur = 0;
        if(
            fileList.length()>0 &&
            file_cnt == 0 &&
            findNumberPart( fileList.at(0).fileName() ) ==0
            )
        {
          newFileList.append( fileList.at(0) );
          file_cnt++;
        }

        int idx=0;
        int idx_1=0;

        while( 
            file_cnt > 0
            && file_cnt < fileList.length() 
            //&&findNumberPart( fileList.at(file_cnt).fileName() ) ==\
            //findNumberPart( fileList.at(file_cnt-1).fileName() )-1
            )
        {
            idx = findNumberPart( fileList.at(file_cnt).fileName() );
            idx_1 = findNumberPart( fileList.at(file_cnt-1).fileName() );
            //qDebug()<<(idx-1==idx_1);
            if(!(idx==idx_1+1) 
               //&& cur_time - start_time < 10
               && cur_time - start_time < piccache_wait_time)
            {
              if(status_wait==false && cur_time==start_time)
              {
                start_time = time(NULL);
              }
              cur_time = time(NULL);

              status_wait = true;

              //qDebug()<<"start:"<<start_time;
              //qDebug()<<"cur:"<<cur_time;
              break;
            }
            else if(!(idx==idx_1+1) && cur_time - start_time >= piccache_wait_time)
            {
              status_wait = false;
              start_time = 0;
              cur_time = 0;
            }

            //qDebug()<<"file_idx:"<<findNumberPart( fileList.at(file_cnt).fileName() );
            //qDebug()<<">>file_name:"<<fileList.at(file_cnt).fileName() ;
            //qDebug()<<">>file_cnt:"<<file_cnt;
            newFileList.append(fileList.at(file_cnt));
            file_cnt++;
        }

        readCount = picList->count();

        //if(readCount < fileList.count())
        //if(file_cur>file_cnt)
        //if(readCount < file_cnt)
        if(newFileList.length()>0)
        {//循环嵌套，大循环刷新文件夹， 小循环把这次刷新到的文件加入缓存
            int newCount;
            for(newCount = 0;newCount < newFileList.count();newCount++)
            {
                pic tmp;
                
                //qWarning("piccache newfile %s", newFileList.at(newCount).fileName());
                //qDebug()<<newFileList.at(newCount).fileName() ;

                if(newFileList.at(newCount).fileName().contains("_"))
                {
                    tmp.uavFlag = true;

                    tmp.uavNum = uavCount;
                    uavCount ++;
                }
                else
                {
                    tmp.uavFlag = false;
                    tmp.uavNum = -1;
                }

                while( tmp.pixmap.load(newFileList.at(newCount).filePath()) == false)
                    msleep(200);
                picWidth = tmp.pixmap.width();
                picHeight = tmp.pixmap.height();
                tmp.uavFlag = -1;
                if((picHeight*1.0 / picWidth) == 0.5625)
                {
                    //qDebug()<<"16:9";
                    tmp.pixmap = tmp.pixmap.scaled(QSize(960, 540), Qt::KeepAspectRatio);
                }
                else
                {
                    tmp.pixmap = tmp.pixmap.scaled(QSize(800, 600), Qt::KeepAspectRatio);
                    //qDebug()<<(picHeight / picWidth);
                }

                picList->append(tmp);

            }
        }
        //else qDebug()<<"缓存快于文件生成";
    }
}



